#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#include "mypipe.h"


struct mypipe_st{         //管道的数据结构  阻塞的 
    int head; 
    int tail;
    char data [PIPESIZE];
    int datasize;
    int count_rd = 0;
    int count_wr = 0 ;
    pthread_mutex_t mut;   //独占
    pthread_cond_t cond;   //通知机制
};

mypipe_t*mypipe_init(void){  //  初始化
    struct mypipe_st *me; 
    me = malloc (sizeof (*me));
    if(me   == NULL)
        return NULL;
    me->head = 0;
    me->tail = 0;
    me->datasize = 0;
    pthread_mutex_init (& me->mut, NULL); 
    pthread_cond_init (& me->cond, NULL);
    
}  
int mypipe_register(mypipe_t *,int opmap){
    /*if error*/
    pthread_mutex_Lock (&me->mut);
    if (opmap & MYPIPE_READ)
        me->count_rd++; 
    if (opmap & MYPIPE_WRITE)
        e->count_wr++; 
    pthread_cond broadcast (&me->cond);
    while(me->count_rd <= 0|| me->count_wr <= 0)  //读者或者写者有一个不存在，都会进行等待另一方到来
        pthread_cond_wait (&me->cond, &me->mut); 

    pthread_mutex_unlock (&me->mut) ;
    return 0;

}
int mypipe_unregister(mypipe_t *,int opmap){
    pthread_mutex_lock (&me->mut); 
    if (opmap & MYPIPE_RD)
        me->count_rd;
    if (opmap & MYPIPE_WR)
        me->count_wr;
    pthread_mutex_unlock (&me->mut);

}
static int mypipe_readbute_unlocked(struct mypipe_st *me , char *datap){
    if(me->datasize <0)
        return -1;
    *datap = me->data [me ->head] ; 
    me->head = next (me->head); 
    me->datasize -- ;
    return 0;

}

int mypipe_read (mypipe_t *,void *buf, size_t count){  //写管道
    struct mypipe_st *me= ptr; 
    pthread_mutex_lock (&me->mut); 
    while (me->datasize <= 0&& me->count_wr > 0)  //没数据，但是写者大于零才等待写者写入
        pthread_cond_wait (&me->cond, &me->mut);
    if (me->datasize <= O && me->count_wr <= 0){   //没有数据，且写者的数量小于等于0  
        pthread_mutex_unlock (&me->mut);  //解锁退出
        return 0;
    }


    for(i = o ; i < count; i++){
        if(mypipe_readbyte_unlocked(me,buf+i)!=0){
            break;
        }
    }
        
    pthread_cond_broadcast (&me->cond);
    pthread_mutex_unlock (&me->mut); 
    return i;
}
int mypipe_write(mypipe_t *, const void *buf, size_t ){ //读管道

} 
int mypipe_destroy (mypipe_t *);{  //销毁
    struct mypipe_st *me = ptr; 
    pthread_mutex_destroy (&me->mut);
    pthread_cond_destroy (&me->cond); 
    free(ptr);
    return 0



}   






